package cn.epsilon3.utils;

import cn.epsilon3.exception.Epsilon3Exception;

import java.util.Optional;
import java.util.function.Supplier;

/**
 * @description 轮询工具类
 * @author: epsilon3
 * @date: 2023/10/23 16:55
 */

public class RetryUtils {

    /**
     * 开始执行轮询任务
     *
     * @param maxTime 最大尝试数
     * @param interval 间隔 ms
     * @param task 任务
     * @return 任务反参
     * @param <T> 任务返回类型
     */
    public static <T> T start(int maxTime, long interval, Supplier<T> task) {
        int numRetries = 0;
        Exception exception = null;
        while (numRetries < maxTime) {
            try {
                return task.get();
            } catch (Exception e) {
                numRetries++;
                exception = Optional.ofNullable(exception).orElse(e);
                if (numRetries >= maxTime) {
                    throw new Epsilon3Exception(exception.getMessage());
                }
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
            }
        }
        throw new Epsilon3Exception("已执行至最大执行数，但均以失败");
    }
}
